package com.atcd.security_redis_jwt.service;

import com.atcd.security_redis_jwt.bean.LoginUser;
import com.atcd.security_redis_jwt.bean.User;
import com.atcd.security_redis_jwt.mapper.UserMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;

import java.util.*;


//认证的时候会调用这个实现类(因为他实现了UserDetailsService接口)
@Service
//登录时实现UserDetailsService接口，实现loadUserByUsername
public class UserDetailServiceImpl implements UserDetailsService  {
    @Autowired
    private UserMapper userMapper;

    public UserDetails loadUserByUsername(String username) throws BadCredentialsException{

        //查询用户信息
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(username),"user_name",username);

        User user = userMapper.selectOne(queryWrapper);
        if(Objects.isNull(user)){
            //如果为null，抛出异常
           throw  new BadCredentialsException("用户名不存在");
        }

        //TODO 根据用户查询权限信息 添加到LoginUser中
        List<String> list = new ArrayList<>(Collections.singletonList("test"));
        return new LoginUser(user,list);
    }
}
